/*
 * Copyright 2012 Dominik.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cz.muni.fi.PA165.musiclibraryweb.song;

import cz.muni.fi.PA165.musiclibraryweb.HomePage;
import cz.muni.fi.PA165.musiclibraryapi.dto.AlbumDTOInterface;
import cz.muni.fi.PA165.musiclibraryapi.dto.AuthorDTOInterface;
import cz.muni.fi.PA165.musiclibraryapi.dto.GenreDTOInterface;
import cz.muni.fi.PA165.musiclibrarybackend.dto.AlbumDTO;
import cz.muni.fi.PA165.musiclibrarybackend.dto.AuthorDTO;
import cz.muni.fi.PA165.musiclibrarybackend.dto.GenreDTO;
import cz.muni.fi.PA165.musiclibrarybackend.dto.SongDTO;
import cz.muni.fi.PA165.musiclibraryapi.services.AlbumService;
import cz.muni.fi.PA165.musiclibraryapi.services.AuthorService;
import cz.muni.fi.PA165.musiclibraryapi.services.GenreService;
import cz.muni.fi.PA165.musiclibraryapi.services.SongService;
import java.io.Serializable;
import java.util.List;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author Dominik
 */
@AuthorizeInstantiation({"ADMIN"})
public class AddSongPage extends HomePage implements Serializable {

    @Autowired
    private SongService service;
    private SongDTO song;

    public AddSongPage(final PageParameters parameters) {
        this(parameters, null);
    }

    public AddSongPage(final PageParameters parameters, SongDTO sdto) {
        super(parameters);
        add(new BookmarkablePageLink("songView", SongPage.class));
        add(new BookmarkablePageLink("songAdd", AddSongPage.class));
        if (sdto == null) {
            song = new SongDTO();
        } else {
            song = sdto;
        }

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        final AlbumService albumService = context.getBean(AlbumService.class);
        final AuthorService authorService = context.getBean(AuthorService.class);
        final GenreService genreService = context.getBean(GenreService.class);
        service = context.getBean(SongService.class);

        final TextField<String> nameField = new TextField("name", new PropertyModel<String>(song, "name"));
        final TextField<Integer> bitField = new TextField("bitrate", new PropertyModel<Integer>(song, "bitrate"));
        final TextField<String> commentField = new TextField("comment", new PropertyModel<String>(song, "comment"));
        final TextField<Integer> orderField = new TextField("order", new PropertyModel<Integer>(song, "songOrder"));

        final DropDownChoice<AlbumDTOInterface> albumMakes = new DropDownChoice<AlbumDTOInterface>("album",
                new PropertyModel<AlbumDTOInterface>(song, "album"),
                new LoadableDetachableModel<List<AlbumDTOInterface>>() {
                    @Override
                    public List<AlbumDTOInterface> load() {
                        return albumService.getAllAlbums();
                    }
                });

        final DropDownChoice<AuthorDTOInterface> authorMakes = new DropDownChoice<AuthorDTOInterface>("author",
                new PropertyModel<AuthorDTOInterface>(song, "author"),
                new LoadableDetachableModel<List<AuthorDTOInterface>>() {
                    @Override
                    public List<AuthorDTOInterface> load() {
                        return authorService.getAllAuthors();
                    }
                });
        final DropDownChoice<GenreDTOInterface> genreMakes = new DropDownChoice<GenreDTOInterface>("genre",
                new PropertyModel<GenreDTOInterface>(song, "genre"),
                new LoadableDetachableModel<List<GenreDTOInterface>>() {
                    @Override
                    public List<GenreDTOInterface> load() {
                        return genreService.getAllGenres();
                    }
                });
        Form<?> form = new Form("form") {
            @Override
            protected void onSubmit() {
                if (nameField.getConvertedInput() == null
                        || nameField.getConvertedInput().equals("")
                        || !authorService.getAllAuthors().contains(authorMakes.getConvertedInput())
                        || !genreService.getAllGenres().contains(genreMakes.getConvertedInput())
                        || !albumService.getAllAlbums().contains(albumMakes.getConvertedInput())) {
                    setResponsePage(new SongPage(parameters,
                            new Label("error", "Song name, album, author and genre should be filled")));
                } else {
                    if (song.getId() == null) {
                        try {
                            service.createSong(song);
                            setResponsePage(SongPage.class);
                        } catch (Exception exception) {
                            setResponsePage(new SongPage(parameters,
                                    new Label("error", "Database error!")));
                        }
                    } else {
                        song.setName(nameField.getConvertedInput());
                        song.setAlbum(albumMakes.getConvertedInput());
                        song.setAuthor(authorMakes.getConvertedInput());
                        song.setGenre(genreMakes.getConvertedInput());
                        song.setBitrate(bitField.getConvertedInput());
                        song.setSongOrder(orderField.getConvertedInput());
                        song.setComment(commentField.getConvertedInput());
                        try {
                            service.updateSong(song);
                            setResponsePage(SongPage.class);
                        } catch (Exception exception) {
                            setResponsePage(new SongPage(parameters,
                                    new Label("error", "Database error!")));
                        }
                    }
                }
            }
        };
        form.add(nameField);
        form.add(albumMakes);
        form.add(authorMakes);
        form.add(genreMakes);
        form.add(bitField);
        form.add(orderField);
        form.add(commentField);

        add(form);
    }
}
